package com.hzw.saas.web.sso.controller.wechat;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.hzw.saas.api.user.IUserTripartiteService;
import com.hzw.saas.api.user.bo.UserWeTripartiteBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.auth.param.WeChatTokenParam;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.service.property.enums.ModuleEnum;
import com.hzw.saas.web.sso.controller.dto.SsoTokenDto;
import com.hzw.saas.web.sso.controller.dto.WechatLoginResponse;
import com.hzw.saas.web.sso.service.ISaasOauthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * 鸿之微云单点登录微信
 *
 * @author sonam
 * @sine 2021/11/23 2:15 下午
 */

@Slf4j
@ApiIgnore
@RestController
@ApiSort(value = 1)
@RequiredArgsConstructor
@Api(tags = "鸿之微/微信登录")
@RequestMapping("/saas/wechat")
public class WechatController {

    private final ISaasOauthService oauthService;
    private final IUserTripartiteService userWeChatService;
    private final UserDetailsService userDetailsService;

    @GetMapping("/login")
    @SysLog(operation = "获取access token")
    public ResponseEntity<WechatLoginResponse> AppSSOByUnionIdAndOpenId(@ApiParam("code") @RequestParam String code,
                                                                @ApiParam("应用类型,前两位系统参数编号，三四位接入方编号，微信01，五六位平台编号，pc端01，app02，七八位对应服务的编号，05010101：网站鸿之微云，05010201：移动端hbox") @RequestParam(defaultValue = "05010101") String type) {
        log.debug("code：{},type: {}", code, type);
        AssertUtil.assertThrow("参数错误", StrUtil.isBlank(code) || StrUtil.isBlank(type));

        WeChatTokenParam wechatByCode = userWeChatService.getWechatByCode(code, type);
        AssertUtil.assertThrow("微信登录异常，请重试", wechatByCode == null || wechatByCode.getOpenid() == null || wechatByCode.getUnionid() == null);

        return ResponseEntity.ok(getSsoTokenInfo(wechatByCode, type));
    }

    private WechatLoginResponse getSsoTokenInfo(WeChatTokenParam weChatTokenParam, String type) {
        String unionId = weChatTokenParam.getUnionid();
        String openId = weChatTokenParam.getOpenid();
        UserWeTripartiteBO userWeTripartiteBO;
        List<UserWeTripartiteBO> userWeTripartiteBOList = userWeChatService.getByUnionId(unionId);
        if (CollectionUtil.isEmpty(userWeTripartiteBOList)) {
            userWeTripartiteBO = new UserWeTripartiteBO();
            userWeTripartiteBO.setOpenId(openId);
            userWeTripartiteBO.setUnionId(unionId);
            userWeTripartiteBO.setModule(ModuleEnum.getDataByCode(type));
            userWeChatService.saveOne(userWeTripartiteBO);
        } else {
            userWeTripartiteBO = userWeTripartiteBOList.get(0);
        }

        WechatLoginResponse response = new WechatLoginResponse();
        response.setUnionId(unionId);
        response.setOpenId(openId);
        // 判断是否绑定了用户
        String userId = userWeTripartiteBO.getUserId();
        if(StrUtil.isNotBlank(userId)) {
            // 绑定了用户
            UserDetails user = userDetailsService.loadUserByUsername(userId);
            SsoTokenDto tokenDto = oauthService.buildSsoToken(user, user.getPassword());
            response.setSsoToken(tokenDto.getSsoToken());
        }
        return response;
    }

}
